//
//  YXYOAuthController.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/6/26.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit
import SVProgressHUD

class YXYOAuthController: UIViewController {

    let web : UIWebView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //view.backgroundColor = randomColor()
        view.backgroundColor = UIColor.whiteColor()
        setUpNav()
        loadOAuth()
    }
    
    override func loadView() {
        
        super.loadView()
        view = web
        web.delegate = self
        
    }
    
    // 设置nav
    private func setUpNav () {
        title = "授权登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "clickBackBtn")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoWrite")
    }
    
    // 按钮的点击事件
    @objc private func clickBackBtn() {
        dismissViewControllerAnimated(true) { () -> Void in
            SVProgressHUD.dismiss()
        }
    }
    @objc private func autoWrite() {
        let jsString = "document.getElementById('userId').value='yuanxiangyang0528@163.com',document.getElementById('passwd').value='yxy8612665'"
        web.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // 加载授权页
    private func loadOAuth () {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(kAppKey)&redirect_uri=\(kAppRedirect_uri)"
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        web.loadRequest(request)
        
    }
}

// MARK: - webView的代理方法
extension YXYOAuthController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 获取 code 字段
        let urlString = request.URL?.absoluteString
        if let u = urlString where u.hasPrefix(kAppRedirect_uri) {
            
            if let query = request.URL?.query {
                let code = query.substringFromIndex("code=".endIndex)
                
                getToken(code)
                
                return false
            }
            
        }
        
        return true
    }
    
}

extension YXYOAuthController {
    
    // 通过code获取token字段
    func getToken(code:String) {
        
        YXYNetWorkTool.sharedWorkTool.loadUserAccount(code, success: { (response) -> () in
            
            // 字典转模型
            guard let res = response as? [String :AnyObject] else {
                return
            }
            
            let userAccount = YXYUserAccount(dict: res)
            
            self.loadUserInfo(userAccount)
            
            }) { (error) -> () in
                
                print(error)
                
        }
        
        
    }
    
    // 通过token获取用户数据
    func loadUserInfo (userAccount: YXYUserAccount) {
        
        YXYNetWorkTool.sharedWorkTool.loadUserInfo(userAccount, success: { (response) -> () in
            
            // 字典转模型
            guard let res = response as? [String : AnyObject] else {
                return
            }
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            
            // 进行归档存储
            YXYUserAccountTool.sharedUserAccountTool.saveUserAccount(userAccount)
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                // 切换欢迎界面
//                let welcome = YXYWelcomeController()
//                UIApplication.sharedApplication().keyWindow?.rootViewController = welcome
                
                NSNotificationCenter.defaultCenter().postNotificationName(kChangeRootVC, object: nil)
                
                SVProgressHUD.dismiss()
            })
            
            }) { (error) -> () in
            
                print(error)
                
        }
        
    }
}